import { createRouter, createWebHashHistory } from 'vue-router'
import ojRoutes from './ojRoutes'
import adminRoutes from "./adminRoutes"
import { ElMessage } from "element-plus"


const routes = [
  {
    path: '/',
    redirect: '/home/homePage'
  },
  {
    path: '/admin',
    redirect: '/admin/dashboard'
  },
  {
    path: '/home',
    name: 'home',
    component: () => import("@/pages/home.vue"),
    children: [
      ...ojRoutes
    ]
  },
  {
    path: '/admin',
    name: 'admin',
    component: () => import("@/pages/adminPage/adminHome.vue"),
    children: [
      ...adminRoutes
    ]
  },
  {
    path: '/:pathMatch(.*)',
    //访问主页的时候 重定向到index页面
    redirect: '/404',
  },
  {
    path: '/404',
    name: '/404',
    component: import("@/components/publicComponents/404Page.vue"),
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


router.beforeEach((to, from, next) => {
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
  //匿名接口直接放行
  if (to.meta.anonymity) {
    next()
  } else {
    if (to.matched[0].path == '/admin') {//后台
      document.title = 'OJ Backend'
      if (userInfo && userInfo?.authLevel == 0) {
        router.push({ path: '/home' })
      } else {
        next()
      }
    } else {//非后台
      if (userInfo) {
        next()
      } else {
        // bus.emit("showLoginDialog")
        ElMessage.error("请登录")
      }
    }
  }
})
export default router